<template>
  <tian-animation>
    <div slot class="fixed-box">
      <div class="move-box">
        <div class="header" ref="move-header-box" v-dragParent>
          <p>
            {{
              isLoginDialogShow == 0
                ? "登录"
                : isLoginDialogShow == 1
                ? "手机号注册"
                : isLoginDialogShow == 2
                ? "邮箱登录"
                : /*3*/ "手机号登录"
            }}
          </p>
          <img
            @click="isloginDialog"
            :src="require('@assets/img/login-chacha.png')"
            alt
          />
        </div>
        <!-- 未登录情况下 -->
        <div class="nologin-content" v-if="isLoginDialogShow == 0">
          <img
            class="img"
            :src="require('@assets/img/login-box-bgimg.png')"
            alt
          />
          <div class="button-box">
            <button class="phone-button" type="button" @click="isLoginBox(3)">
              手机号登录
            </button>
            <button class="email-button" type="button" @click="isLoginBox(2)">
              163邮箱登录
            </button>
            <button
              class="register-button"
              type="button"
              @click="isLoginBox(1)"
            >
              注&nbsp;&nbsp;&nbsp;册
            </button>
          </div>
        </div>

        <!-- 注册账号 -->
        <div class="nologin-content" v-if="isLoginDialogShow == 1">
          <div class="margin-auto">
            <div class="input-box">
              <p class="label">手机号:</p>
              <input
                type="text"
                v-model="registerConfig.phone"
                placeholder="请输入手机号"
                @focus="registerConfig.isPhoneError = false"
                :class="registerConfig.isPhoneError ? 'isPhoneError' : ''"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
              />
              <p class="label">密码:</p>
              <input
                type="password"
                v-model="registerConfig.password"
                placeholder="设置登录密码，不少于8位"
                @focus="registerConfig.isPasswordError = false"
                @input="registerVaild"
                maxlength="20"
                :class="registerConfig.isPasswordError ? 'isPhoneError' : ''"
              />
              <div class="error-message" v-if="registerConfig.isPhoneError">
                <div class="img">
                  <img :src="require('@assets/img/login-error-icon.png')" />
                </div>
                <span>请输入正确的手机号</span>
              </div>
              <div class="error-message">
                <div class="img">
                  <img
                    v-if="!registerConfig.isPasswordBlankError"
                    :src="require('@assets/img/login-success-icon.png')"
                  />
                  <img
                    v-else
                    :src="require('@assets/img/login-error-icon.png')"
                  />
                </div>
                <span>密码不能包含空格</span>
              </div>
              <div class="error-message">
                <div class="img">
                  <img
                    v-if="!registerConfig.isPasswordTwoError"
                    :src="require('@assets/img/login-success-icon.png')"
                  />
                  <img
                    v-else
                    :src="require('@assets/img/login-error-icon.png')"
                  />
                </div>
                <span>包含字母、数字、符号中至少两种</span>
              </div>
              <div class="error-message">
                <div class="img">
                  <img
                    v-if="!registerConfig.isPasswordLengthError"
                    :src="require('@assets/img/login-success-icon.png')"
                  />
                  <img
                    v-else
                    :src="require('@assets/img/login-error-icon.png')"
                  />
                </div>
                <span>密码长度为8-20位</span>
              </div>
            </div>
            <div class="button-box">
              <button
                :disabled="registerConfig.phoneLoginLoading ? true : false"
                class="phone-button"
                type="button"
                @click="registerLoginSave"
              >
                {{ registerConfig.phoneLoginLoading ? "下一步..." : "下一步" }}
              </button>
            </div>
          </div>
          <FooterBackComponent :isLoginBox="isLoginBox" :isLoginBoxNum="1" />
        </div>
        <!-- 获取验证码 -->
        <div class="nologin-content" v-if="isLoginDialogShow == 5">
          <div class="margin-auto">
            <div class="code_message_warning">
              <p class="you_phone">
                <span>你的手机号：</span>
                <span class="color_black">{{
                  registerConfig.phone.replace(/(\d{3})\d*(\d{4})/, "$1****$2")
                }}</span>
              </p>
              <p class="txt">为了安全，我们会给你发送短信验证码</p>
            </div>
            <div class="code_input_box">
              <input
                @input="nextCodeInput(1, $event)"
                ref="code_input"
                class="code_input"
                :style="{
                  'border-bottom': registerConfig.code1
                    ? '2px solid #B82712'
                    : '',
                }"
                type="text"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="1"
                v-model="registerConfig.code1"
              />
              <input
                @input="nextCodeInput(2, $event)"
                ref="code_input"
                class="code_input"
                :style="{
                  'border-bottom': registerConfig.code2
                    ? '2px solid #B82712'
                    : '',
                }"
                type="text"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="1"
                v-model="registerConfig.code2"
              />
              <input
                @input="nextCodeInput(3, $event)"
                ref="code_input"
                class="code_input"
                :style="{
                  'border-bottom': registerConfig.code3
                    ? '2px solid #B82712'
                    : '',
                }"
                type="text"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="1"
                v-model="registerConfig.code3"
              />
              <input
                ref="code_input"
                class="code_input"
                :style="{
                  'border-bottom': registerConfig.code4
                    ? '2px solid #B82712'
                    : '',
                }"
                type="text"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="1"
                v-model="registerConfig.code4"
              />
            </div>
            <div
              v-if="registerConfig.codeCountTimeout == 0"
              class="resetCode"
              @click="codeCount"
            >
              <span>重新发送</span>
            </div>
            <div v-else class="resetCode" style="cursor: context-menu">
              <span>{{ registerConfig.codeCountTimeout }}</span>
            </div>
            <div class="button-box margin-top-20">
              <button
                class="phone-button"
                type="button"
                @click="registerLoginCodeSave"
              >
                {{ registerConfig.phoneLoginLoading ? "下一步..." : "下一步" }}
              </button>
            </div>
          </div>
          <footerRegisterComponent :isLoginBox="isLoginBox" />
        </div>

        <!-- 163 邮箱登录 -->
        <div class="nologin-content" v-if="isLoginDialogShow == 2">
          <div class="margin-auto">
            <div class="input-box">
              <input
                type="text"
                v-model="emailConfig.email"
                placeholder="请输入账号"
                @focus="emailConfig.isPhoneError = false"
                :class="emailConfig.isPhoneError ? 'isPhoneError' : ''"
              />
              <input
                style="margin-top: 20px"
                type="password"
                v-model="emailConfig.password"
                placeholder="请输入密码"
                @focus="emailConfig.isPasswordError = false"
                maxlength="20"
                :class="emailConfig.isPasswordError ? 'isPhoneError' : ''"
              />
              <div
                class="error-message"
                v-if="
                  emailConfig.isPhoneError ||
                  emailConfig.isPasswordError ||
                  emailConfig.showError
                "
              >
                <div class="img">
                  <img :src="require('@assets/img/login-error-icon.png')" />
                </div>
                <span class="color-red">{{ emailConfig.errMessage }}</span>
              </div>
            </div>
            <div class="button-box" style="margin-top: 10px">
              <button
                :disabled="emailConfig.emailLoginLoading ? true : false"
                class="phone-button"
                type="button"
                @click="emailLoginSave"
              >
                {{ phoneConfig.phoneLoginLoading ? "登录..." : "登录" }}
              </button>
            </div>
          </div>
          <FooterComponent :isLoginBox="isLoginBox" />
        </div>

        <!-- 手机号登录 -->
        <div class="nologin-content" v-if="isLoginDialogShow == 3">
          <div class="margin-auto">
            <div class="input-box">
              <p class="label">手机号:</p>
              <input
                type="text"
                v-model="phoneConfig.phone"
                placeholder="请输入手机号"
                @focus="phoneConfig.isPhoneError = false"
                :class="phoneConfig.isPhoneError ? 'isPhoneError' : ''"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
              />
              <p class="label">密码:</p>
              <input
                type="password"
                v-model="phoneConfig.password"
                placeholder="请输入密码"
                @focus="phoneConfig.isPasswordError = false"
                maxlength="20"
                :class="phoneConfig.isPasswordError ? 'isPhoneError' : ''"
              />
              <div
                class="error-message"
                v-if="
                  phoneConfig.isPhoneError ||
                  phoneConfig.isPasswordError ||
                  phoneConfig.showError
                "
              >
                <div class="img">
                  <img :src="require('@assets/img/login-error-icon.png')" />
                </div>
                <span class="color-red">{{ phoneConfig.errMessage }}</span>
              </div>
            </div>
            <div class="button-box">
              <button
                :disabled="phoneConfig.phoneLoginLoading ? true : false"
                class="phone-button"
                type="button"
                @click="phoneLoginSave"
              >
                {{ phoneConfig.phoneLoginLoading ? "登录..." : "登录" }}
              </button>

              <!-- <button
              :disabled="phoneConfig.phoneLoginLoading?true:false"
              class="register-button"
              type="button"
              @click="isLoginBox(3)"
            >验证码登录</button>-->
            </div>
          </div>
          <FooterComponent :isLoginBox="isLoginBox" />
        </div>

        <!-- 验证码登录 -->
        <div class="nologin-content" v-if="isLoginDialogShow == 4">
          <div class="margin-auto">
            <div class="input-box">
              <p class="label">手机号:</p>
              <input
                v-focus
                type="text"
                v-model="phoneConfig.phone"
                placeholder="请输入手机号"
                @focus="phoneConfig.isPhoneError = false"
                :class="phoneConfig.isPhoneError ? 'isPhoneError' : ''"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
              />
              <p class="label">密码:</p>
              <input
                type="password"
                v-model="phoneConfig.password"
                placeholder="请输入密码"
                @focus="phoneConfig.isPasswordError = false"
                maxlength="20"
                :class="phoneConfig.isPasswordError ? 'isPhoneError' : ''"
              />
              <div
                class="error-message"
                v-if="
                  phoneConfig.isPhoneError ||
                  phoneConfig.isPasswordError ||
                  phoneConfig.showError
                "
              >
                <div class="img">
                  <img :src="require('@assets/img/login-error-icon.png')" />
                </div>
                <span class="color-red">{{ phoneConfig.errMessage }}</span>
              </div>
            </div>
            <div class="button-box">
              <button
                :disabled="phoneConfig.phoneLoginLoading ? true : false"
                class="phone-button"
                type="button"
                @click="phoneLoginSave"
              >
                {{ phoneConfig.phoneLoginLoading ? "登录..." : "登录" }}
              </button>

              <button
                :disabled="phoneConfig.phoneLoginLoading ? true : false"
                class="register-button"
                type="button"
                @click="isLoginBox(3)"
              >
                验证码登录
              </button>
            </div>
          </div>
          <FooterComponent :isLoginBox="isLoginBox" />
        </div>
      </div>
    </div>
  </tian-animation>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import FooterComponent from "./Footer";
import FooterBackComponent from "./FooterBack";
import footerRegisterComponent from "./FooterRegister";

import {
  loginCellphone,
  testHtml,
  loginEmail,
  registerCellphone,
  cellphoneExistenceCheck,
  captchaSent,
  userLevel,
} from "@/api";

export default {
  name: "loginDialog",
  components: {
    FooterComponent,
    FooterBackComponent,
    footerRegisterComponent,
  },
  props: {
    // 0 == 初始界面  1 == 注册账号  2 == 163 邮箱登录  3 == 手机号登录  4 == 手机验证码登录 5 == 获取验证码
    isLoginDialogShow: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      phoneConfig: {
        phone: "",
        password: "",
        errMessage: "", // 请输入正确手机号
        isPhoneError: false,
        isPasswordError: false,
        showError: false,
        phoneLoginLoading: false,
      },
      emailConfig: {
        email: "",
        password: "",
        errMessage: "", // 请输入正确邮箱
        isPhoneError: false,
        isPasswordError: false,
        showError: false,
        phoneLoginLoading: false,
      },
      registerConfig: {
        phone: "",
        password: "",
        errMessage: "", // 请输入正确手机号
        isPhoneError: false, // 输入框 手机号
        isPasswordError: false, // 输入框 密码
        isPasswordBlankError: false, // 密码空格报错
        isPasswordTwoError: false, // 数字 字母 符号 两种
        isPasswordLengthError: false, // 8--20位
        phoneLoginLoading: false,
        showError: false,
        code1: null,
        code2: null,
        code3: null,
        code4: null,
        codeCountTimeout: 0,
      },
    };
  },
  computed: {},
  created() {
    document.onkeydown = (e) => {
      let key = window.event.keyCode;
      if (key == 27) {
        this.isloginDialog();
      }
    };
  },
  destroyed: {
    focus: {
      inserted: function (el) {
        el.focus();
      },
    },
  },
  methods: {
    ...mapActions("common", [
      "SET_CHANGE_LOGIN_DIALOG",
      "SET_CHANGE_LOGIN_DIALOG_SHOW",
    ]),
    ...mapActions("user", ["SET_CHANGE_USER_INFO"]),
    // 初始化登录框
    isloginDialog() {
      this.SET_CHANGE_LOGIN_DIALOG();
      this.isLoginBox(0);
    },
    isLoginBox(val) {
      this.SET_CHANGE_LOGIN_DIALOG_SHOW(val);
    },
    // 手机号登录
    phoneLoginSave() {
      if (!this.phoneConfig.phone) {
        this.phoneConfig.isPhoneError = true;
        this.phoneConfig.errMessage = "请输入手机号";
        return;
      }
      if (!/^1[3456789]\d{9}$/.test(this.phoneConfig.phone)) {
        this.phoneConfig.isPhoneError = true;
        this.phoneConfig.errMessage = "请输入正确的手机号";
        return;
      }
      if (!this.phoneConfig.password) {
        this.phoneConfig.isPasswordError = true;
        this.phoneConfig.errMessage = "请输入密码";
        return;
      }
      this.phoneConfig.phoneLoginLoading = true;
      let { phone, password } = this.phoneConfig;
      loginCellphone({ phone, password }).then((data) => {
        this.phoneConfig.phoneLoginLoading = false;
        if (data.code !== 200) {
          this.phoneConfig.showError = true;
          this.phoneConfig.errMessage = data.message;
        }
        this.SET_CHANGE_USER_INFO(data);
        this.isloginDialog();
      }).catch(err=>{
        this.phoneConfig.phoneLoginLoading = false;
      })
    },

    // 邮箱登录
    emailLoginSave() {
      if (!this.emailConfig.email) {
        this.emailConfig.isPhoneError = true;
        this.emailConfig.errMessage = "请输入邮箱";
        return;
      }
      if (
        !/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.]){1,2}[A-Za-z\d]{2,5}$/g.test(
          this.emailConfig.email
        )
      ) {
        this.emailConfig.isPhoneError = true;
        this.emailConfig.errMessage = "请输入正确的邮箱";
        return;
      }
      if (!this.emailConfig.password) {
        this.emailConfig.isPhoneError = true;
        this.emailConfig.errMessage = "请输入密码";
        return;
      }
      this.emailConfig.phoneLoginLoading = true;
      let { email, password } = this.emailConfig;
      loginEmail({ email, password }).then((data) => {
        this.emailConfig.phoneLoginLoading = false;
        if (data.code !== 200) {
          this.emailConfig.showError = true;
          this.emailConfig.errMessage = data.message;
        }
        this.SET_CHANGE_USER_INFO(data);
        this.isloginDialog();
      }).catch(err=>{
        this.emailConfig.phoneLoginLoading = false;
      })
    },
    // 注册
    registerVaild() {
      let flag = false;
      // 验证空格
      if (/(\s)/.test(this.registerConfig.password.toString())) {
        this.registerConfig.isPasswordBlankError = true;
      } else {
        this.registerConfig.isPasswordBlankError = false;
      }
      // 验证 数字 字母
      if (
        /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]/.test(
          this.registerConfig.password
        )
      ) {
        this.registerConfig.isPasswordTwoError = false;
      } else {
        this.registerConfig.isPasswordTwoError = true;
      }
      if (this.registerConfig.password.length < 8) {
        this.registerConfig.isPasswordLengthError = true;
      } else {
        this.registerConfig.isPasswordLengthError = false;
      }
      if (flag) return;
    },
    async registerLoginSave() {
      if (!this.registerConfig.phone) {
        this.registerConfig.isPhoneError = true;
        return;
      }
      if (!/^1[3456789]\d{9}$/.test(this.registerConfig.phone)) {
        this.registerConfig.isPhoneError = true;
        return;
      }
      if (!this.registerConfig.password) {
        this.registerConfig.isPasswordError = true;
        return;
      }
      if (
        this.registerConfig.isPhoneError ||
        this.registerConfig.isPhoneError ||
        this.registerConfig.isPasswordError ||
        this.registerConfig.isPasswordBlankError ||
        this.registerConfig.isPasswordTwoError ||
        this.registerConfig.isPasswordLengthError
      ) {
        return;
      }
      this.registerConfig.phoneLoginLoading = true;
      let captchaSentMessage = false;

      await captchaSent({ phone: this.registerConfig.phone })
        .then((data) => {
          this.registerConfig.phoneLoginLoading = false;
        })
        .catch((err) => {
          captchaSentMessage = true;
          this.registerConfig.phoneLoginLoading = false;
        });
      if (captchaSentMessage) return;
      this.isLoginBox(5);
    },
    registerLoginCodeSave() {
      if (
        !this.registerConfig.code1 ||
        !this.registerConfig.code2 ||
        !this.registerConfig.code3 ||
        !this.registerConfig.code4
      ) {
        this.$notify({
          title: "提示",
          message: "请输入验证码",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      this.registerConfig.phoneLoginLoading = true;
      // 检测是否注册过
      cellphoneExistenceCheck({ phone: this.registerConfig.phone }).then(
        async (data) => {
          let notify;
          if (data.exist == 1 && data.code == 200) {
            notify = this.$notify({
              title: "提示",
              message: "手机号已被注册, 请直接登录",
              type: "warning",
              duration: 0,
            });
            // 登录
            this.registerConfig.phoneLoginLoading = false;
            this.isLoginBox(3);
          } else {
            this.registerConfig.phoneLoginLoading = false;

            // 注册
            registerCellphone({
              phone: this.registerConfig.phone,
              password: this.registerConfig.password,
              // nickname: ,
              captcha:
                this.registerConfig.code1 +
                this.registerConfig.code2 +
                this.registerConfig.code3 +
                this.registerConfig.code4,
            }).then((data) => {
              this.SET_CHANGE_USER_INFO(data);
              this.isloginDialog();
              notify ? notify.close() : "";
            });
          }
        }
      );
    },
    nextCodeInput(val, e) {
      if (!val) return;
      if (!e.data) return;
      document.querySelectorAll(".code_input")[val].focus();
    },
    codeCount() {
      let captchaSentMessage = false;
      captchaSent({ phone: this.registerConfig.phone })
        .then((data) => {
          this.registerConfig.phoneLoginLoading = false;
        })
        .catch((err) => {
          this.registerConfig.phoneLoginLoading = false;
        });
      if (captchaSentMessage) return;
      this.registerConfig.codeCountTimeout = 60;
      let timer = setInterval(() => {
        this.registerConfig.codeCountTimeout--;
        if (this.registerConfig.codeCountTimeout == 0) {
          clearInterval(timer);
          timer = null;
        }
      }, 1000);
    },
  },
  destroyed() {
    document.onkeydown = null;
  },
};
</script>

<style lang="scss" scoped>
.resetCode {
  width: 100%;
  font-size: 12px;
  color: #0c73c2;
  margin-top: 10px;
  margin-right: 10px;
  text-align: right;
  cursor: pointer;
}
.margin-top-20 {
  margin-top: 10px;
}
.code_message_warning {
  font-size: 12px;
  color: #999;
  .you_phone {
    color: #666;
  }
  .color_black {
    color: #333;
  }
  .txt {
  }
}
.code_input_box {
  margin-top: 20px;
  display: flex;
  .code_input {
    color: #666;
    transition: all 1s;
    margin: 0 8px;
    border-top: none;
    border-left: none;
    border-right: none;
    width: 40px;
    text-align: center;
    font-size: 24px;
  }
}
.fixed-box {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2001;
  .move-box {
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 5px 16px rgba(0, 0, 0, 0.8);
    position: absolute;
    left: calc(50% - 265px);
    // right: 0;
    top: calc(50% - 186px);
    // bottom: 0;
    // margin: auto;
    width: 530px;
    height: 372px;
    .header {
      -moz-user-select: none;
      -khtml-user-select: none;
      user-select: none;
      cursor: move;
      background-color: #2d2d2d;
      padding: 0 20px;
      font-weight: 600;
      color: #fff;
      display: flex;
      justify-content: space-between;
      height: 38px;
      font-size: 14px;
      line-height: 38px;
      align-items: center;
      img {
        width: 20px;
        height: 20px;
        cursor: pointer;
        margin-right: -5px;
      }
    }
    // 未登录情况下
    .nologin-content {
      position: relative;
      height: 334px;
      box-sizing: border-box;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      box-sizing: border-box;
      .margin-auto {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }
      .error-message {
        font-size: 12px;
        color: #333;
        margin-top: 5px;

        display: flex;
        align-items: center;
        .img {
          margin-right: 7px;
          margin-top: 0;
          width: 14px;
          height: 14px;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .input-box {
        display: flex;
        flex-direction: column;

        .label {
          font-size: 12px;
          margin: 10px 0;
          color: #333;
        }

        input {
          width: 206px;
          height: 19px;
          margin: 0;
          padding: 5px 6px 6px;
          border: 1px solid #cdcdcd;
          border-radius: 2px;
          box-sizing: content-box;
          font-size: 12px;
          color: #333;
          font-family: Arial, Helvetica, sans-serif;
        }
      }
      .img {
        margin-top: 10px;
        width: 200px;
      }
      .button-box {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        .phone-button,
        .email-button,
        .register-button {
          width: 220px;
          height: 30px;
          border: 0;
          outline: 0;
          border-radius: 3px;
          margin-top: 10px;
          text-align: center;
          font-size: 12px;
          color: #fff;
          cursor: pointer;
        }
        .phone-button,
        .email-button {
          background-image: linear-gradient(#4da1e0, #1d6ebe);
          border: 1px solid #3984ce;
        }
        .register-button {
          border: 1px solid #c4c4c4;
          background-image: linear-gradient(#ffffff, #f1f1f1);
          color: #333;
        }
      }
    }
  }
}
.color-red {
  color: #e33232;
}
.isPhoneError {
  border: 1px solid #f08b8b !important;
  color: #c20c0c !important;
}
</style>